package com.hsp.socket;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author Stringzhua
 * @Date 2024/3/26 19:58
 * description:服务器端
 * 9999监听socket
 * 思路:
 * 1.socket.getOutputStream()
 * 2.写入数据到数据通道
 * 3.关闭socket和IO对象...
 */
@SuppressWarnings("all")
public class SocketTCP02Server {
    public static void main(String[] args) throws IOException {
        //1.在本机的9999端口监听，等待连接
        //细节:要求在本机没有其他的服务占用9999端口
        //细节:ServerSocket 可以通过accept() 返回多个Socket[多并发]【即多个客户端连接服务器的情况】
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端口监听,等待连接");
        //2.当无客户端连接9999端口时,程序会阻塞,等待连接
        //如果有客户端连接,则会返回一个socket对象,程序继续往下执行
        Socket socket = serverSocket.accept();
        System.out.println("服务器端 socket=" + socket.getClass());
        //3.通过socket.getInputStream()读取客户端写入到数据通道的数据,显示
        InputStream inputStream = socket.getInputStream();
        //4.IO读取
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf)) != -1) {
            System.out.println(new String(buf, 0, readLen));
            //根据读取到的实际长度，显示内容.
        }
        //5.获取socket相关联的输出流socket.getOutputStream
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,cilent".getBytes());
        //设置结束标记
        socket.shutdownOutput();
        //6.关闭流和socket
        inputStream.close();
        outputStream.close();
        socket.close();
        serverSocket.close();//关闭
        System.out.println("服务器端退出");
    }
}
